#include <json/json.h>
#include <iostream>
#include <string>
#include <sstream>
#include <memory>

bool serialize(const Json::Value &root, std::string &str)
{
    Json::StreamWriterBuilder swb;
    std::unique_ptr<Json::StreamWriter> sw(swb.newStreamWriter());
    std::stringstream ss;
    int ret = sw->write(root, &ss);
    if (ret < 0)
    {
        std::cout << "json serialize failed" << std::endl;
        return false;
    }

    str = ss.str();
    return true;
}

bool deserialize(const std::string &body, Json::Value &val)
{
    Json::CharReaderBuilder crb;
    std::unique_ptr<Json::CharReader> cr(crb.newCharReader());
    std::string err;
    bool ret = cr->parse(body.c_str(), body.c_str() + body.size(), &val, &err);
    if (ret == false)
    {
        std::cout << "json deserialize failed " << err << std::endl;
        return false;
    }
    return true;
}

int main()
{
    std::string name = "小明";
    int age = 18;
    float score[3] = {91, 99, 100};

    Json::Value stu;
    stu["name"] = name;
    stu["age"] = age;
    stu["score"].append(score[0]);
    stu["score"].append(score[1]);
    stu["score"].append(score[2]);

    std::string json_str;

    bool ret = serialize(stu, json_str);
    if (ret == false)
    {
        std::cout << "json serialize failed" << std::endl;
        return -1;
    }
    std::cout << json_str << std::endl;

    Json::Value root;
    ret = deserialize(json_str, root);
    if (ret == false)
    {
        std::cout << "json deserialize failed" << std::endl;
        return -1;
    }

    std::cout << "姓名:" << root["name"].asString() << std::endl;
    std::cout << "年龄:" << root["age"].asInt() << std::endl;
    std::cout << "成绩分别是: ";
    int sz = root["score"].size();
    for (int i = 0; i < sz; i++)
    {
        std::cout << root["score"][i].asFloat() << " ";
    }
    std::cout << std::endl;
    return 0;
}